package com.smasher.bluetooth.scan;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.util.Log;

import androidx.annotation.RequiresPermission;

import java.util.ArrayList;
import java.util.List;

public class DiscoveringBle extends BaseDiscovering {


    public static final String TAG = "BleDiscovering";

    private BluetoothLeScanner bleScanner;

    public DiscoveringBle(Context context) {
        super(context);
    }

    // 扫描回调
    private final ScanCallback scanCallback = new ScanCallback() {
        @SuppressLint("MissingPermission")
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            BluetoothDevice device = result.getDevice();
            if (mDeviceFoundListener != null) {
                mDeviceFoundListener.onDeviceFound(device);
            }
        }

        @Override
        public void onScanFailed(int errorCode) {
            Log.e(TAG, "扫描失败，错误码: " + errorCode);
            handleScanError(errorCode);
        }
    };


    @Override
    public void init(Context context) {

    }

    @RequiresPermission(Manifest.permission.BLUETOOTH_SCAN)
    @Override
    public void startDiscovering() {
        if (bleScanner == null) {
            bleScanner = bluetoothAdapter.getBluetoothLeScanner();
        }

        // 扫描配置
        ScanSettings settings = new ScanSettings.Builder()
                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                .build();

        // 扫描过滤器（可选）
        List<ScanFilter> filters = new ArrayList<>();

        // 开始扫描
        bleScanner.startScan(filters, settings, scanCallback);
        Log.e(TAG, "BLE 扫描已启动");

        mHandler.postDelayed(new Runnable() {
            @SuppressLint("MissingPermission")
            @Override
            public void run() {
                bleScanner.stopScan(scanCallback);
            }
        }, 12000);
    }

    @RequiresPermission(Manifest.permission.BLUETOOTH_SCAN)
    @Override
    public void stopDiscovering() {
        if (bleScanner != null) {
            bleScanner.stopScan(scanCallback);
        }
    }


    @Override
    public void release(Context context) {
        super.release(context);
    }


    private void handleScanError(int errorCode) {
        switch (errorCode) {
            case ScanCallback.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED:
                // 等待系统资源释放后重试
                mHandler.postDelayed(this::restartScan, 2000);
                break;

            case ScanCallback.SCAN_FAILED_FEATURE_UNSUPPORTED:
                // 设备不支持BLE
                Log.e("BleScanner", "设备不支持BLE");
                break;

            case ScanCallback.SCAN_FAILED_INTERNAL_ERROR:
                // 内部错误，尝试重启蓝牙
//                restartBluetooth();
                break;

            case ScanCallback.SCAN_FAILED_ALREADY_STARTED:
                // 已经在扫描了
                break;
        }
    }

    @RequiresPermission(Manifest.permission.BLUETOOTH_SCAN)
    private void restartScan() {
        if (bluetoothAdapter.isEnabled()) {
            startDiscovering();
        }
    }

}
